package com.extrace.loader;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import com.extrace.misc.model.UserInfo;
import com.extrace.net.HttpAsyncTask;
import com.extrace.net.HttpResponseParam;
import com.extrace.net.IDataAdapter;
import com.extrace.net.JsonUtils;
import com.extrace.ui.main.ExTraceApplication;
import com.google.gson.reflect.TypeToken;

public class UserLoader extends HttpAsyncTask{

    String url;
    public static boolean flag = false;
    IDataAdapter<UserInfo> adapter;
    private Activity context;

    public UserLoader(IDataAdapter<UserInfo> adapt,Activity context) {
        super(context);
        this.context = context;
        adapter = adapt;
        url = ((ExTraceApplication)context.getApplication()).getMiscServiceUrl();
    }

    @Override
    public void onDataReceive(String class_name, String json_data) {
        if(class_name.equals("UserInfo"))
        {
            UserInfo ui = JsonUtils.fromJson(json_data, new TypeToken<UserInfo>(){});
            ((ExTraceApplication)context.getApplication()).UserLogin(ui);
            adapter.setData(ui);
            adapter.notifyDataSetChanged();
        }
        else if(JsonUtils.fromJson(json_data,new TypeToken<Boolean>(){})) {
            Toast.makeText(context,"登录成功!", Toast.LENGTH_SHORT).show();
            flag = true;
        } else {
            Toast.makeText(context,"账号或者密码错误!", Toast.LENGTH_SHORT).show();
            flag = false;
        }
    }

    @Override
    public void onStatusNotify(HttpResponseParam.RETURN_STATUS status, String str_response) {
        Log.i("onStatusNotify", "onStatusNotify: " + str_response);
    }

    public void Login(int userID, String pwd)
    {
        url += "doLogin/" + userID + "/" + pwd + "?_type=json";
        try{
            execute(url, "GET");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void GetUserInfo(int userID)
    {
        url += "getUserInfo/" + userID + "?_type=json";
        try {
            execute(url, "GET");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
